<?php declare(strict_types=1);

/**
 * @package SimpleMenu (Light Portal)
 * @link https://custom.simplemachines.org/index.php?mod=4244
 * @author Bugo <bugo@dragomano.ru>
 * @copyright 2021-2025 Bugo
 * @license https://spdx.org/licenses/GPL-3.0-or-later.html GPL-3.0-or-later
 *
 * @category plugin
 * @version 05.11.25
 */

namespace LightPortal\Plugins\SimpleMenu;

use Bugo\Compat\Config;
use Bugo\Compat\Utils;
use LightPortal\Enums\Tab;
use LightPortal\Plugins\Block;
use LightPortal\Plugins\Event;
use LightPortal\Plugins\PluginAttribute;
use LightPortal\UI\Fields\CustomField;
use LightPortal\Utils\Str;
use LightPortal\Utils\Traits\HasView;

if (! defined('LP_NAME'))
	die('No direct access...');

/**
 * Generated by PluginMaker
 */
#[PluginAttribute(icon: 'far fa-list-alt')]
class SimpleMenu extends Block
{
	use HasView;

	public function prepareBlockParams(Event $e): void
	{
		$e->args->params['items'] = '';

		$data = $this->post()->only(['item_name', 'item_link']);

		$items = [];
		if ($data && isset($data['item_name']) && isset($data['item_link'])) {
			foreach ($data['item_name'] as $key => $item) {
				if (empty($link = $data['item_link'][$key]))
					continue;

				$items[] = [
					'name' => $item,
					'link' => $link,
				];
			}

			$this->post()->put('items', json_encode($items, JSON_UNESCAPED_UNICODE));
		}
	}

	public function validateBlockParams(Event $e): void
	{
		$e->args->params['items'] = FILTER_DEFAULT;
	}

	public function prepareBlockFields(Event $e): void
	{
		CustomField::make('items', $this->txt['items'])
			->setTab(Tab::CONTENT)
			->setValue($this->view(params: ['options' => $e->args->options]));
	}

	public function getData(string $items): array
	{
		if (empty($items)) {
			return [];
		}

		$ul = Str::html('ul', ['class' => 'dropmenu']);

		$items = Utils::jsonDecode($items, true);

		foreach ($items as $item) {
			[$title, $link] = [$item['name'], $item['link']];

			$ext = true;
			if (! str_starts_with((string) $link, 'http')) {
				$active = $link == Utils::$context['current_action'];
				$link   = Config::$scripturl . '?action=' . $link;
				$ext    = false;
			}

			$li = Str::html('li', ['style' => 'width: 100%']);
			$a = Str::html('a', [
				'href'   => $link,
				'class'  => empty($active) ? null : 'active',
				'target' => empty($ext) ? null : '_blank',
				'rel'    => empty($ext) ? null : 'noopener',
			])->setText($title);

			$li->addHtml($a);
			$ul->addHtml($li);
		}

		return ['content' => $ul->toHtml()];
	}

	public function prepareContent(Event $e): void
	{
		$parameters = $e->args->parameters;

		if (empty($parameters['items']))
			return;

		$html = $this->cache($this->name . '_addon_b' . $e->args->id)
			->setLifeTime($e->args->cacheTime)
			->setFallback(fn() => $this->getData($parameters['items']));

		if (empty($html))
			return;

		echo $html['content'] ?? '';
	}
}
